/* Created by FINAL PYTON 88 */

package pl.edu.agh.admin.gui;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;

import pl.edu.agh.admin.api.CronTabManager;
import pl.edu.agh.admin.api.CronTabManagerProvider;
import pl.edu.agh.admin.api.User;



public class UserPanel extends JPanel implements ActionListener
{
	private static final long serialVersionUID = 1888;
	
	private JCheckBox[] userCheckBoxes;
	private User[] users;
	private JButton selectAllButton;
	private JButton deselectAllButton;
	
	private TaskTableModel taskTableModel;
	private TimeAxisPanel timeAxisPanel;
	

	public UserPanel(TaskTableModel taskTableModel, TimeAxisPanel timeAxisPanel)
	{
		this.taskTableModel = taskTableModel;
		this.timeAxisPanel = timeAxisPanel;

		CronTabManager cronTabMgr = CronTabManagerProvider.getCronTabManager();
		users = cronTabMgr.getUseres().toArray(new User[0]);
		
		
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(users.length, 2, 5, 5));

		int i = 0;
		userCheckBoxes = new JCheckBox[users.length];
		for(User u : users)
		{
			userCheckBoxes[i] = new JCheckBox(u.getName());
			panel.add(userCheckBoxes[i]);
			userCheckBoxes[i].addActionListener(this);
			
			JLabel label = new JLabel("[]");
			label.setForeground(FinalPytonUserColorier.getUserColor(u));
			panel.add(label);
			
			i++;
		}

		JPanel selectButtonPanel = new JPanel();
		selectButtonPanel.setLayout(new GridLayout(2, 1, 5, 5));

		selectAllButton = new JButton("Zaznacz wszystko");
		selectAllButton.addActionListener(this);
		selectButtonPanel.add(selectAllButton);

		deselectAllButton = new JButton("Odznacz wszystko");
		deselectAllButton.addActionListener(this);
		selectButtonPanel.add(deselectAllButton);

		add(panel);
		add(selectButtonPanel);
	}



	public void actionPerformed(ActionEvent event)
	{
				
		if(event.getSource() == selectAllButton)
		{
			for(JCheckBox checkBox : userCheckBoxes)
				checkBox.setSelected(true);
		}else if(event.getSource() == deselectAllButton)
		{
			for(JCheckBox checkBox : userCheckBoxes)
				checkBox.setSelected(false);			
		}
		
		List<User> selectedUsers = new LinkedList<User>();
		for(int i = 0; i < userCheckBoxes.length; i++)
			if(userCheckBoxes[i].isSelected())
				selectedUsers.add(users[i]);

		taskTableModel.filtrByUsers(selectedUsers);
		taskTableModel.fireTableDataChanged();
		
		timeAxisPanel.setSelectedUsers(selectedUsers);
		timeAxisPanel.repaint();
	}
}
